<template>
  <div :style="commpStyle" class="commonTable">
    <div class="box-card el-card__body">
      <div class="btn-crud">
        <!-- 工具栏装饰器，用于渲染传入进来的组件 -->
        <div v-if="toolbar.custom" class="toolBarClass">
          <layout-container :layout="toolbar.custom"></layout-container>
        </div>
        <div v-if="toolbar.columnPage.visible" class="screen_item"
             :style="{height: toolbar.columnPage.height+'px', width: toolbar.columnPage.width+'px'}">
          <span class="screen_item_arrow">
              <el-button
                type="primary"
                style="padding: 5px"
                :disabled="tableHeaderTempStartIndex==0"
                @click="deleteAll"
              ><i class="el-icon-d-arrow-left"></i
              ></el-button>
              <el-button
                type="primary"
                style="padding: 5px"
                :disabled="tableHeaderTempStartIndex==0"
                @click="prevOption"
              ><i class="el-icon-arrow-left"></i
              ></el-button>
              <el-button
                type="primary"
                style="padding: 5px"
                :disabled="tableHeaderTempEndIndex >= tableHeaderSecond.length-1"
                @click="nextOption"
              ><i class="el-icon-arrow-right"></i
              ></el-button>
              <el-button
                type="primary"
                style="padding: 5px"
                :disabled="tableHeaderTempEndIndex >= tableHeaderSecond.length-1"
                @click="checkAll"
              ><i class="el-icon-d-arrow-right"></i
              ></el-button>
          </span>
          <el-select
            class="columnSelect"
            multiple
            collapse-tags
            v-model="visibleHeader"
            @change="selectChange"
            size="small"
            @visible-change="visibleSelect"
            :popper-append-to-body="false"
            placeholder="筛选列名"
          >
            <el-option
              v-for="item in tableHeader"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            ></el-option>
          </el-select>
        </div>
      </div>
      <el-table
        :height="localTableHeight"
        :max-height="localTableMaxHeight"
        empty-text="暂无数据..."
        style="width: 100% ; height: 100%"
        :header-cell-style="getRowClass"
        ref="multipleTable"
        :data="localTableData"
        tooltip-effect="dark"
        :header-cell-class-name="tableHeaderCellClass"
        @select-all="selectAll"
        :row-class-name="rowClassName"
        @selection-change="selectionLineChangeHandle"
        @row-click="rowClickFunc"
        @select="rowSelectFun"
        @cell-dblclick="dbEvent"
        @row-dblclick="dbRowClickFunc"
        @cell-click="cellClick"
        :expand-row-keys="expandRowKeys"
        @expand-change="expandChange"
        :row-key="rowKey"
        node-key="nodeKey"
        :lazy="lazy"
        :load="loadMethod"
        :default-expand-all="defaultExpandAll"
        :tree-props="treeProps"
      >
        <!-- 多选 -->
        <el-table-column align="center" type="selection" width="55"
                         v-if="isMultiple && !expand"></el-table-column>
        <!-- 单选 -->
        <el-table-column width="55" align="center" type="selection" label="选择" v-if="isRadio && !expand">
          <template slot-scope="scope">
            <el-radio v-model="radio" :label="scope.row[rowKey]"></el-radio>
          </template>
        </el-table-column>
        <el-table-column type="expand" width="20" align="center" v-else-if="expand">
          <template slot-scope="scope">
            <component :is="getComponent(expandRender)" v-model="scope.row"
                       v-bind="getComponentParams(expandRender)" v-on="getComponentEvent(expandRender)"
                       :multiple="false">
            </component>
          </template>
        </el-table-column>
        <!-- 自定义列的遍历-->
        <template v-for="(item,index) in tableHeaderTemp">
          <el-table-column
            show-overflow-tooltip
            :header-align="item.headerAlign || item.align || 'left'"
            :align="item.align || 'left'"
            :width="item.width || 'auto'"
            v-if="item.visible || true"
            :key="'tableHeader_'+index"
            :label="item.label"
            :property="item.key"
            :reserve-selection="true"
          >
            <!-- 表头内容提示，当数据量较多时通过title方式提示用户 -->
            <template slot="#header">
              <div @mouseover="onMouseOver('rFollowUpEntityList')">
                <el-tooltip :disabled="isShowTooltip" :content="item.label" placement="top-start">
                  <div class="long_title"><span ref="rFollowUpEntityList">{{ item.label }}</span>
                  </div>
                </el-tooltip>
              </div>
            </template>

            <!-- 数据的遍历  scope.row就代表数据的每一个对象-->
            <template v-slot="scope">
              <component v-if="getSubComponent(tableHeaderRender, '*', index)"
                         :is="getSubComponent(tableHeaderRender, '*', index)"
                         v-bind="getSubComponentParams(tableHeaderRender, '*', index, item, scope.row)"
                         v-on="getSubComponentEvent(tableHeaderRender, '*', index)"
                         v-model="scope.row[item.key]">
                <span v-if="getSubComponentHtml(tableHeaderRender, '*', index)"
                      v-html="getSubComponentHtml(tableHeaderRender, '*', index)"></span>
              </component>
              <span v-else v-html="getFormatter(item,scope.row,scope.row)"></span>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <el-pagination
        v-if="pageBar.visible"
        small
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="Number(pageBar.pageNum)"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="Number(pageBar.pageSize)"
        :popper-class="'commonTablePagination'"
        layout="total, sizes, prev, pager, next, jumper"
        :total="Number(pageBar.total)"
      ></el-pagination>
    </div>
  </div>
</template>
<script>

import layoutContainer from "./layoutContainer";
import BaseComp from "./baseComp"

export default {
  name: "commonTable",
  model: {
    prop: "value",
    event: "tabListChange",
  },
  extends: BaseComp,
  components: {
    layoutContainer
  },
  props: {
    expandRowKeys: {
      type: Array,
      default: () => [],
    },
    //是否懒加载
    lazy: {
      type: Boolean,
      default: () => false,
    },
    //树形表格，属性配置
    treeProps: {
      type: Object,
      default: () => {
        return {
          children: 'children',
          hasChildren: 'leaf'
        }
      }
    },

    //表格数据
    tableList: {
      type: Array,
      required: true,
      default: () => [],
    },
    //列是否展开
    defaultExpandAll: {
      type: Boolean,
      default: false,
    },
    // 控制表格是否多选操作
    isMultiple: {
      type: Boolean,
      default: true,
    },
    // 控制表格是否多选操作
    isRadio: {
      type: Boolean,
      default: false,
    },
    //是否展开行
    expand: {
      type: Boolean,
      default: false,
    },
    //是否支持双击事件
    dbEventStatus: {
      type: Boolean,
      default: false,
    },
    // 不能被修改的列
    dbNotUpdateColumn: {
      type: Array,
      default: () => [],
    },
    //表格高度
    tableHeight: {
      type: [Number, String],
      default: null
    },
    //表格最大高度
    tableMaxHeight: {
      type: [Number, String],
      default: null
    },
    //行标识
    rowKey: {
      type: String,
      default: 'id'
    },
    columnMaxNum: { //表格展示最大列
      type: Number,
      default: 8
    },
    //行标识
    nodeKey: {
      type: String,
      default: 'id'
    },


    //******************************************
    //通过v-mode传递过来的数据
    value: {
      type: [Array, String]
    },
    // 表头工具栏配置
    toolbar: {
      type: Object,
      default: () => {
        return {
          //列分页
          columnPage: {
            visible: true,
            width: 'auto',
            height: 'auto'
          },
          //自定义组件区域
          custom: {
            row: 1,
            col: 24,
            render: [
              {
                rowNum: 1,
                colNum: 1,
                component: '',
                width: '',
                height: ''
              }
            ]
          }
        }
      }
    },
    //表头
    tableHeader: {
      type: Array,
      required: true,
      default: () => [],
    },
    //表格行内容渲染
    tableHeaderRender: {
      type: Array,
      required: false,
      default: () => [],
    },
    //展开行渲染配置
    expandRender: {
      type: Object,
    },
    pageBar: {
      type: Object,
      default: () => {
        return {
          visible: true,
          pageSize: 10,
          pageNum: 1,
          total: 0
        }
      }
    }
  },
  data() {
    return {
      isShowTooltip: false,
      // expandRowKeys: [],
      version: "", // 版本
      deleteDisabled: false,
      prevDisabled: false,
      nextDisabled: true,
      checkDisabled: true,
      toggleHeadList: [], //切换的表头数据
      HeaderList: [], //筛选选中的数组
      multipleSelection: [], // 选中
      visibleHeader: [], //选中的表头数据字段
      moreBtn: [], //控制更多按钮
      tableBtns: [], //控制按钮
      radio: '',
      tableHeaderSecond: [],
      tableHeaderTemp: [], //临时表头存储
      tableHeaderTempStartIndex: 0, // 临时表头存储的开始索引
      tableHeaderTempEndIndex: 7, // 临时表头存储的结束索引
      tableHeaderTempMaxSize: 8, //临时表头存储的最大长度
      localTableHeight: null,
      localTableMaxHeight: null,
      localTableData: [],
    };
  },
  watch: {
    tableHeader: {
      handler(newVal) {
        this.tableHeaderTemp = []
        this.tableHeaderSecond = []
        newVal.forEach((obj) => {
          if (obj.visible) {
            this.tableHeaderSecond.push(obj)
          }
        })
        window.setTimeout(() => {
          this.tableHeaderTempEndIndex = this.tableHeaderTempStartIndex + this.tableHeaderTempMaxSize - 1
          //特别注意，不能用箭头函数，箭头函数，this指向全局
          this.initTableHeader();
        }, 500)

      },
      immediate: true, //刷新加载 立马触发一次handler
      deep: true, // 可以深度检测到 obj 对象的属性值的变化
    },

    columnMaxNum: {
      handler(newVal) {
        this.tableHeaderTempMaxSize = newVal
        this.tableHeaderTempEndIndex = this.tableHeaderTempStartIndex + this.tableHeaderTempMaxSize - 1
      },
      immediate: true, //刷新加载 立马触发一次handler
      deep: true, // 可以深度检测到 obj 对象的属性值的变化
    },
    tableHeight: {
      handler(newVal) {
        //特别注意，不能用箭头函数，箭头函数，this指向全局
        if (newVal) {
          this.localTableHeight = newVal;
        } else {
          this.localTableHeight = null;
        }
      },
      immediate: true, //刷新加载 立马触发一次handler
      deep: true
    },
    tableMaxHeight: {
      handler(newVal) {
        //特别注意，不能用箭头函数，箭头函数，this指向全局
        if (newVal) {
          this.localTableMaxHeight = newVal;
        } else {
          this.localTableMaxHeight = null;
        }
      },
    },
    tableList: {
      handler(newVal) {
        //特别注意，不能用箭头函数，箭头函数，this指向全局
        if (newVal) {
          this.$set(this, 'localTableData', newVal);
          console.log(this.localTableData)
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    // this.initTableButton();
  },
  mounted() {
    this.loadTheme(this.$options.name);
  },
  computed: {},
  methods: {
    vModelBindValue(row, item) {
      if (item) {
        let itemElement = item['formatter'];
        if (typeof itemElement == "function") {
          return itemElement(row[item.key], row);
        } else {
          return row[item.key];
        }
      }
    },
    onMouseOver() {
      //   let parentWidth = 0
      //   if (this.$refs[refName].parentNode) {
      //     parentWidth = this.$refs[refName].parentNode.offsetWidth;
      //   }
      //   let contentWidth = this.$refs[refName].offsetWidth;
      // 开启tooltip功能
      this.isShowTooltip = false;
      // 判断是否开启tooltip功能
      // if (contentWidth > parentWidth) {
      //   this.isShowTooltip = false;
      // } else {
      //   this.isShowTooltip = false;
      // }
    },
    /**
     * 获取行索引
     */
    getRowIndex(row) {
      return row.index
    },
    disableMethod(row, item) {
      let flag = false;
      if (item.disableValues && item.disableKey) {
        for (let i = 0; i < item.disableValues.length; i++) {
          let val = item.disableValues[i];
          if (val == row[item.disableKey]) {
            flag = true;
            break;
          }
        }
        return flag;
      }
      return false;
    },
    /**
     * 表格选中事件
     */
    selectionLineChangeHandle(val) {
      //获取所有选中数据
      this.multipleSelection = val;
      //上传到父级事件
      this.$emit("tableSelected", this.multipleSelection);
      //传递v-mode绑定对象
      this.$emit("tabListChange", this.multipleSelection);
    },
    // 懒加载方法
    loadMethod(row, treeNode, resolve) {
      this.$emit("loadMethod", row, treeNode, resolve);
    },
    //点击单元格事件
    cellClick(row, column, cell, event) {
      this.$emit("cellClick", row, column, cell, event);
    },
    //行展开事件
    expandChange(row, expand) {
      this.$emit('expandChange', row, expand);
    },
    /**
     * 根据当前表格是否可多选，设置表头全选框样式。
     * 如当前表格为单选时，则隐藏表头全选按钮，否则显示。
     * 如当前表格为单选时，则隐藏表头全选按钮，否则显示。
     */
    tableHeaderCellClass(row) {
      if (row.columnIndex === 0) {
        if (this.isRadio) {

          return "disableSelectionAll";
        }
      }
    },
    /**
     * 初始化表格操作按钮
     */
    // initTableButton() {
    //   this.moreBtn = [];
    //   this.tableBtns = [];
    //   let index = 1;
    //   for (let btn in this.btns) {
    //     let button = this.btns[btn];
    //     if (button && button.name) {
    //       if (index < 4) {
    //         this.tableBtns.push(button);
    //       } else {
    //         this.moreBtn.push(button);
    //       }
    //     }
    //     index++;
    //   }
    // },
    /**
     * 初始化表头选中状态
     */
    initTableHeader() {
      let tableHeaderTemp_ = new Set();
      for (let i = this.tableHeaderTempStartIndex; i <= this.tableHeaderTempEndIndex; i++) {
        let header = this.tableHeaderSecond[i];
        if (header && header.visible) {
          //存储临时表头
          tableHeaderTemp_.add(header);
        }
      }
      //设置下拉框需要默认选中的表头数据
      if (this.tableHeaderTemp.length == 0) {
        this.visibleHeader = this.tableHeader.map((obj) => {
          if (obj.visible) {
            return obj.key;
          }
        }).join(",").split(',')
      }
      this.tableHeaderTemp = Array.from(tableHeaderTemp_);
    },
    //修改表头显示与隐藏数据
    changeTableHeader(val) {
      console.log(val)
      //获取当默认选中的表头key集合
      let defaultHeaderSet = new Set();
      this.tableHeaderTemp.forEach((header) => {
        if (header.visible) {
          defaultHeaderSet.add(header.key);
        }
      });
      //获取当前已经发生变化的表头key集合
      let changeValSet = new Set(val);
      let selectSet;
      //当变化的表头集合小于默认表头时，说明用户在减少当前需要显示的表头数据，反之则是用户在增加当前显示的表头数据
      if (changeValSet.size < defaultHeaderSet.size) {
        //获取两个Set集合中的交集
        selectSet = new Set(
          [...defaultHeaderSet].filter((x) => changeValSet.has(x))
        );
      } else {
        //获取两个Set集合中的并集
        selectSet = new Set([...defaultHeaderSet, ...changeValSet]);
      }
      //设置表头显示与否
      this.tableHeaderTemp.forEach((header) => {
        if (selectSet.has(header.key)) {
          header.visible = true;
        } else {
          header.visible = false;
        }
      });
    },
    /**
     * 下拉框表头选中变化时触发函数
     */
    // selectChange(val) {
    //   if (val.length > 2) {
    //     let a = []
    //     for (let i = 0; i < val.length; i++) {
    //       let b = this.tableHeader.filter(item => item.key == val[i])
    //       if (b.length > 0) {
    //         a.push(b[0])
    //       }
    //     }
    //     debugger
    //     this.tableHeaderSecond = a
    //     // this.changeTableHeader(val);
    //     const lis = document.getElementsByClassName(
    //       "el-select-dropdown__item"
    //     );
    //     for (let i = 0; i < lis.length; i++) {
    //       const element = lis[i];
    //       // 必须使用nextTick 否则拿不到最新的修改后的dom选中状态 也就没法判断
    //       this.$nextTick(() => {
    //         // 判断当前的li是否被选中 选中的则设置复选框被选中
    //         if (element.classList.contains("selected")) {
    //           element.firstChild.checked = true;
    //         } else {
    //           element.firstChild.checked = false;
    //         }
    //       });
    //     }
    //     this.deleteAll()
    //   } else {
    //     this.$message.warning("必须大于2个")
    //     return false
    //   }
    // },
    /**
     * 下拉框表头选中变化时触发函数
     */
    selectChange(val) {
      if (val.length > 2) {
        let a = []
        for (let i = 0; i < val.length; i++) {
          let b = this.tableHeader.filter(item => item.key == val[i])
          if (b.length > 0) {
            a.push(b[0])
          }
        }
        let sortHeader = this.sortHeader(a, this.tableHeader);
        //将新的数组进行排序
        this.$set(this, 'tableHeaderTemp', sortHeader);
        // this.tableHeaderTemp = sortHeader
        // this.changeTableHeader(val);
        let lis = document.getElementsByClassName("columnSelect")[0].querySelectorAll('.el-select-dropdown__item');
        for (let i = 0; i < lis.length; i++) {
          const element = lis[i];
          // 必须使用nextTick 否则拿不到最新的修改后的dom选中状态 也就没法判断
          this.$nextTick(() => {
            // 判断当前的li是否被选中 选中的则设置复选框被选中
            if (element.classList.contains("selected")) {
              element.firstChild.checked = true;
            } else {
              element.firstChild.checked = false;
            }
          });
        }
        // this.deleteAll()
      } else {
        this.$message.warning("必须大于2个")
        return false
      }
    },
    sortHeader(a, table) {
      let newArr = []
      if (table && a) {
        for (let i = 0; i < table.length; i++) {
          let filter = a.filter(item => item.key == table[i].key);
          if (filter.length > 0) {
            newArr.push(filter[0])
          }
        }
      }
      return newArr
    },
    /**
     * 下拉框下拉或隐藏时事件
     * @param e
     */
    visibleSelect(e) {
      // 获取所有的li
      let lis = document.getElementsByClassName("columnSelect")[0].querySelectorAll('.el-select-dropdown__item');
      // 打开下拉框 添加input
      if (e) {
        for (let i = 0; i < lis.length; i++) {
          const element = lis[i];
          const input = document.createElement("input");
          input.style.cssText = "margin-right: 10px;";
          input.type = "checkbox";
          // 根据是否有选中的类名来判断li是否被选中
          if (element.classList.contains("selected")) {
            // 对应复选框也设置被选中
            input.checked = true;
          }
          element.insertBefore(input, element.lastChild);
        }
      } else {
        // 关闭下拉框 移除掉input--否则每次打开添加就是多个input
        for (let i = 0; i < lis.length; i++) {
          const element = lis[i];
          element.removeChild(element.firstChild);
        }
      }
    },
    //把表格头变成灰色
    getRowClass({rowIndex}) {
      if (rowIndex === 0) {
        return "background: #FAFAFA;border-bottom:#E8E8E8!impotant;color: #333333;";
      } else {
        return "";
      }
    },

    // 表格中选中的数据
    handleSelectionChange(val) {
      console.log("选中", val);
      this.multipleSelection = val;
      // 推送选中的数据
    },
    //行点击事件，将当前行切换为选中状态
    rowClickFunc(row, column, event) {
      if (this.isMultiple) {
        this.$refs.multipleTable.toggleRowSelection(row);
      } else {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.setCurrentRow(row);
        this.multipleSelection = [row];
        //上传到父级事件
        this.$emit("tableSelected", this.multipleSelection);
      }
      if (this.isRadio) {
        this.radio = row[this.rowKey];
      }
      //回传行点击事件
      this.$emit("rowClick", row, column, event);
    },
    //点击行的Checkbox事件,多选时会触发，单选不触发
    rowSelectFun(selection, row) {
      if (this.isMultiple) {
        // this.$refs.multipleTable.toggleRowSelection(row,true);
      } else {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.setCurrentRow(row);
      }
      if (this.isRadio) {
        this.radio = row[this.rowKey];
      }
      this.setRowIsSelect(row)
      //获取所有选中数据
      this.multipleSelection = selection;
      //上传到父级事件
      this.$emit("tableSelected", this.multipleSelection);
    },
    // 复选框点击事件
    setRowIsSelect(row) {
      // 为空字符串则对应行半选态，点击则应该变为全选，则为true
      if (row.isSelect === '') {
        this.$refs.multipleTable.toggleRowSelection(row, true)
      }
      row.isSelect = !row.isSelect
      const _this = this
      // 判断操作的是子级点复选框还是父级点复选框，如果是父级点，则控制子级点的全选和不全选

      // 1、只是父级 2、既是子集，又是父级 3、只是子级
      const levelStatus = getCurrentLevel(row)

      if (levelStatus === 1) {
        // 操作的是父级，则所有子集同步父级状态
        selectAllChildren(row.children)
      } else if (levelStatus === 2) {
        selectAllChildren(row.children)
        operateLastLevel(row)
      } else if (levelStatus === 1) {
        operateLastLevel(row)
      }

      // 判断当前操作行的层级状态
      function getCurrentLevel(row) {
        // 1、只是父级 2、既是子集，又是父级 3、只是子级
        // 1、只是父级 2、既是子集，又是父级 3、只是子级
        if (row.parentId === undefined) {
          return 1
        } else if (row.parentId && !(row.children && row.children.length)) {
          return 2
        } else {
          return 3
        }
      }

      // 递归处理children子级数据的isSelect状态以及对选框状态
      function selectAllChildren(children) {
        children && children.length && children.forEach((item) => {
          item.isSelect = row.isSelect
          _this.toggleRowSelection(item, row.isSelect)
          if (item.children && item.children.length) {
            selectAllChildren(item.children)
          }
        })
      }

      // 子级向上操作父级状态
      function operateLastLevel(row) {
        // 操作的是子节点,则
        // 1、获取父节点
        // 2、判断子节点选中个数，如果全部选中则父节点设为选中状态，如果都不选中，则为不选中状态，如果部分选择，则设为不明确状态
        const item = getExplicitNode(_this.localTableData, row.parentId)
        const selectStatusArr = getSelectStatus([], item.children)

        // 判断所有子集选中态，都为true则父级也选中，都为false则不选中，否则为半选
        const allSelected = selectStatusArr.every(selectItem => selectItem === true)
        const allUnselected = selectStatusArr.every(selectItem => selectItem === false)
        if (allSelected) {
          item.isSelect = true
          _this.toggleRowSelection(item, true)
        } else if (allUnselected) {
          item.isSelect = false
          _this.toggleRowSelection(item, false)
        } else {
          item.isSelect = ''
        }
        // 如果当前节点的parentId存在，则还有父级，继续递归往上一层操作
        if (item.parentId !== undefined) {
          operateLastLevel(item)
        }
      }

      // 递归获取所有子级的选中状态数组
      function getSelectStatus(selectStatusArr, children) {
        if (!children || !children.length) {
          return selectStatusArr
        }
        children.forEach((child) => {
          selectStatusArr.push(child.isSelect)
          if (child.children && child.children.length) {
            getSelectStatus(selectStatusArr, child.children)
          }
        })
        return selectStatusArr
      }

      // 获取明确父级的节点
      function getExplicitNode(tableData, parentId) {
        let result = null

        function findNode(data) {
          for (let i = 0; i < data.length; i++) {
            if (data[i].partIndex === parentId) {
              result = data[i]
              break
            }
            if (data[i].children && data[i].children.length) {
              findNode(data[i].children)
            }
          }
        }

        findNode(tableData)
        return result
      }
    },
    // 表格全选事件
    selectAllFun(selection) {
      const firstLevelStatus = this.localTableData.map(item => item.isSelect)
      // 判断一级是否是全选.如果一级产品全为true，则设置为取消全选，否则全选
      const isAllSelect = firstLevelStatus.every(status => status)
      // 设置所以一级和二级为选中状态
      this.localTableData.forEach((item) => {
        item.isSelect = isAllSelect
        this.toggleRowSelection(item, !isAllSelect)
        this.rowSelectFun(selection, item)
      })
    },
    // 设置当前行的选中态
    toggleRowSelection(row, flag) {
      if (row) {
        this.$nextTick(() => {
          this.$refs.multipleTable &&
          this.$refs.multipleTable.toggleRowSelection(row, flag)
        })
      }
    },

    // 操作按钮点击
    handleBtnClick(clickType, row) {
      this.$emit("handleBtnClick", {clickType: clickType, row: row});
    },
    //改变数据大小
    handleSizeChange(val) {
      this.pageBar.pageSize = val;
      this.$emit("pageChange", this.pageBar);
    },

    // 改变当前页
    handleCurrentChange(val) {
      this.pageBar.pageNum = val;
      this.$emit("pageChange", this.pageBar);
    },
    deleteAll() {
      this.tableHeaderTempStartIndex = 0
      this.tableHeaderTempEndIndex = this.tableHeaderTempStartIndex + this.tableHeaderTempMaxSize - 1
      this.initTableHeader()
    },
    prevOption() {
      if (this.tableHeaderTempStartIndex != 0) {
        --this.tableHeaderTempStartIndex
        --this.tableHeaderTempEndIndex
      }
      this.initTableHeader()
    },
    nextOption() {
      if (this.tableHeaderTempEndIndex <= this.tableHeaderSecond.length - 1) {
        ++this.tableHeaderTempEndIndex
        ++this.tableHeaderTempStartIndex
      }
      this.initTableHeader()
    },
    checkAll() {
      this.tableHeaderTempEndIndex = this.tableHeaderSecond.length - 1
      this.tableHeaderTempStartIndex = (this.tableHeaderTempEndIndex - this.tableHeaderTempMaxSize) + 1
      this.initTableHeader()
    },
    selectAll(selection) {
      this.selectAllFun()
      this.$emit("selectAll", selection);
    },

    /**
     * 列双击事件
     * @param row 当前行
     * @param column 当前列属性
     * @param cell 当前列
     * @param event 点击事件
     */
    dbEvent(row, column, cell, event) {
      if (
        this.dbNotUpdateColumn.includes(column.property) ||
        column.label == "操作"
      ) {
        this.$message.info("此列数据不能被修改！");
        return;
      }
      let _this = this;
      if (this.dbEventStatus) {
        let str = `<div class="cell">
                  <div class="el-input">
                      <input type="text" class="el-input__inner"/>
                  </div>
              </div>`;
        let InputVal = event.target.textContent;
        cell.innerHTML = str;
        // 获取双击后生成的input 层级嵌套变化
        let cellInput = cell.children[0].children[0].children[0];
        cellInput.value = InputVal;
        cellInput.focus();
        cellInput.onblur = function () {
          let blurInput = `<div class="cell">${cellInput.value}</div>`;
          cell.innerHTML = blurInput;
          row[column.property] = cellInput.value;
          // 返回整体数据和被修改那一栏的数据
          _this.$emit("sure", {
            item: row,
            column: cellInput.value,
            isSave: false,
          });
        };
        this.$emit("dbEvent", row);
        this.$emit("dbCellEvent", {row, column, cell, event});
      }
    },
    rowClassName({row, rowIndex}) {
      row.index = rowIndex
    },
    /**
     * 行双击事件
     * @param row
     * @param column
     * @param event
     */
    dbRowClickFunc(row, column, event) {
      this.$emit("dbRowClickFunc", {row, column, event});
    },
    /**
     * 显示值转换
     * @param item 表头项
     * @param value 当前值
     * @param row 当前行
     */
    getFormatter(item, value, row) {
      if (item.formatter && typeof item.formatter == 'function') {
        let formatter = item.formatter(value, row);
        return formatter
      } else if (item.formatter && typeof item.formatter != 'function') {
        let formatter = eval(item.formatter);
        return formatter(value, row);
      } else {
        return value;
      }
    },
    /**
     * 获取传入进来的组件名
     * @param rowIndex 行索引  this.toolbar.custom.render
     * @param colIndex 列索引
     */
    getSubComponent(dataList, rowIndex, colIndex) {
      let component = dataList.find(item => (item.rowNum == '*' || item.rowNum - 1 == rowIndex) && item.colNum - 1 == colIndex);
      if (!component) {
        return undefined;
      }
      let compName = this.getComponent(component);
      return compName;
    },
    /**
     * 获取组件渲染参数
     * @param dataList 数据集
     * @param rowIndex 行索引
     * @param colIndex 列索引
     * @param tableHeader 当前列表头
     * @param row 当前行数据
     * @returns {string|*}
     */
    getSubComponentParams(dataList, rowIndex, colIndex, tableHeader, row) {
      let component = dataList.find(item => (item.rowNum == '*' || item.rowNum - 1 == rowIndex) && item.colNum - 1 == colIndex);
      //获取dicData内容
      let dicData = row[tableHeader.key + 'DicData']
      component.dicData = dicData;
      let vbParams = this.getComponentParams(component);
      // 格式化数据
      this.getFormatter(tableHeader, row[tableHeader.key], row)
      // props传参
      vbParams.inData = row || {};
      vbParams.tableHeader = tableHeader || {};
      return vbParams;

    },

    /**
     * 获取组件事件
     */
    getSubComponentEvent(dataList, rowIndex, colIndex) {
      let component = dataList.find(item => (item.rowNum == '*' || item.rowNum - 1 == rowIndex) && item.colNum - 1 == colIndex);
      return this.getComponentEvent(component);
    },
    /**
     * 获取组件html
     */
    getSubComponentHtml(dataList, rowIndex, colIndex) {
      let component = dataList.find(item => (item.rowNum == '*' || item.rowNum - 1 == rowIndex) && item.colNum - 1 == colIndex);
      return this.getComponentHtml(component);
    },
    /**
     * 获取组件样式 this.toolbar.custom.render
     * @param rowIndex
     * @param colIndex
     * @returns {{width: *, height: *}}
     */
    getComponentStyle(dataList, rowIndex, colIndex) {
      let component = dataList.find(item => (item.rowNum == '*' || item.rowNum - 1 == rowIndex) && item.colNum - 1 == colIndex);
      if (component) {
        return {
          width: component.width + "px",
          height: component.height + "px"
        }
      }
    },
  },
};
</script>
<style lang="less" scoped>

</style>
